package com.duniptech.engine.core.simulation;

import com.duniptech.engine.core.modeling.api.ICoupled;
import com.duniptech.engine.core.modeling.api.IDevs;
import com.duniptech.engine.core.simulation.api.IRTCentralCoordinator;

public class RTCentralCoordinator extends Coordinator implements IRTCentralCoordinator {
	
	protected long numIterations;
	protected Thread myThread;

	public RTCentralCoordinator(ICoupled digraph) {
		super(digraph);
		super.initialize(System.currentTimeMillis()/1000);
		numIterations = 0;
		myThread = new Thread(this);
	}
	
	public void simulate(long numIterations) {
		this.numIterations = numIterations;
		myThread.start();
	}
	
	public void run() {
		double t = tN;
		long counter;
		for(counter=1; counter<numIterations && t<IDevs.INFINITY; counter++) {
			while(System.currentTimeMillis() < 1000*t - 10) {
				long timeSleeping = (long)(1000*t - System.currentTimeMillis());
				if(timeSleeping>=0) {
					try {
						Thread.sleep(timeSleeping);
					}
					catch(Exception ee) {
						ee.printStackTrace();
					}
				}
			}
			lambda(t);
			deltfcn(t);
			t = tN;
		}
		System.out.println(counter + " iterations.");
	}
	
}

